package com.lzc.tlmail.tlmailproduct.exception;

import com.lzc.common.exception.BizCodeEnume;
import com.lzc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzc
 * @create 2020-07-30 15:30
 */
@Slf4j
//这个注解作用统一处理异常
@RestControllerAdvice(basePackages = "com.lzc.tlmail.tlmailproduct.app")
public class TlmailExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> objectObjectHashMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            objectObjectHashMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",objectObjectHashMap);
    }
    @ExceptionHandler(value =Throwable.class)
    public R exceptionHandle(Throwable t){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
